﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
using System.Data.Odbc;
using System.Collections.Specialized;

namespace EuroAudit
{
    public partial class Login : System.Web.UI.Page
    {
        DataSet GetData(String queryString, String CNStringName)
        {
            string s1="";
            string s2="";
            s1 += "e";
            s2 += "E";
            s1 += "a";
            s2 += "A";
            s1 += "u";
            s2 += "!";
            s1 += "s";
            s2 += "2";
            s1 += "e";
            s2 += "i";
            s1 += "r";
            s2 += "n";

            // Retrieve the connection string stored in the Web.config file.
            string ProvName = ConfigurationManager.ConnectionStrings[CNStringName].ProviderName;
            String connectionString = ConfigurationManager.ConnectionStrings[CNStringName].ConnectionString;
            connectionString = string.Format(connectionString, s1, s2);

            DataSet ds = new DataSet();

            try
            {
                // Connect to the database and run the query.
                if (ProvName == "MySql.Data.MySqlClient")
                {
                    MySqlConnection connection = new MySqlConnection(connectionString);
                    // Connect to the database and run the query.
                    //connection.ConnectionTimeout = 100;
                    connection.Open();
                    MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, connection);
                    adapter.SelectCommand.CommandTimeout = 100;
                    // Fill the DataSet.
                    adapter.Fill(ds);
                    /*if (GetLastInsertID == true)
                    {
                        queryString = "SELECT LAST_INSERT_ID() as LID";
                        adapter = new MySqlDataAdapter(queryString, connection);
                        adapter.Fill(ds, "tLID");
                    }*/
                    connection.Close();
                }
                if (ProvName == "System.Data.Odbc")
                {
                    OdbcConnection connection = new OdbcConnection(connectionString);
                    // Connect to the database and run the query.
                    connection.ConnectionTimeout = 100;
                    connection.Open();
                    OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection);
                    adapter.SelectCommand.CommandTimeout = 100;
                    // Fill the DataSet.
                    adapter.Fill(ds);
                    /*if (GetLastInsertID == true)
                    {
                        queryString = "SELECT LAST_INSERT_ID() as LID";
                        adapter = new OdbcDataAdapter(queryString, connection);
                        adapter.Fill(ds, "tLID");
                    }*/
                    connection.Close();
                }

            }
            catch (Exception ex)
            {

                // The connection failed. Display an error message.
                //Message.Text = "Unable to connect to the database.";


            }

            return ds;

        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] == null || Session["UserName"].ToString() == "" || Session["UserName"].ToString() == "guest")
            {
                Login1.Visible = true;
                Login1.Focus();
                cmdLogOut.Visible = false;
                if (!Page.IsPostBack)
                {
                    GlobalF gf = new GlobalF();
                    gf.InitO();
                }
            }
            else
            {
                Login1.Visible = false;
                cmdLogOut.Visible = true;
            }

        }

        protected bool CheckWrongLogin()
        {
            bool CanLogin = false;
            string qrCheck = "";
            DataSet dsLastLogin = null;
            int Count = 0;
            DateTime LastTime;
            DateTime PreviousTime;
            int WLC = Convert.ToInt32(GlobalF.AppOptions.GetValues("WLoginCount")[0]);
            double WLBT = Convert.ToDouble(GlobalF.AppOptions.GetValues("WLoginBlockTime")[0]);
            if (WLC <= 0)
            {
                CanLogin = true;
            }
            if (WLBT > 0)
            {
                qrCheck = "SELECT *, CURRENT_TIMESTAMP as CT FROM logincount WHERE UserName = '" + Login1.UserName + "'";
                dsLastLogin = GetData(qrCheck, "WebCNS");
                if (dsLastLogin.Tables.Count > 0)
                {
                    if (dsLastLogin.Tables[0].Rows.Count > 0)
                    {
                        Count = Convert.ToInt32(dsLastLogin.Tables[0].Rows[0]["WCount"]);
                        PreviousTime = Convert.ToDateTime(dsLastLogin.Tables[0].Rows[0]["Laiks"]);
                        LastTime = Convert.ToDateTime(dsLastLogin.Tables[0].Rows[0]["CT"]);
                        if (PreviousTime.AddSeconds(WLBT) < LastTime)
                        {
                            CanLogin = true;
                        }
                        else
                        {
                            CanLogin = (WLC > Count);
                        }
                    }
                    else
                    {
                        CanLogin = true;
                    }
                }

            }
            else
            {
                CanLogin = true;
            }

            return CanLogin;
        }

        protected void AddWrongLogin()
        {
            string qrCheck = "";
            DataSet dsLastLogin = null;
            int Count = 0;
            DateTime LastTime;
            DateTime PreviousTime;
            int WLC = Convert.ToInt32(GlobalF.AppOptions.GetValues("WLoginCount")[0]);
            double WLBT = Convert.ToDouble(GlobalF.AppOptions.GetValues("WLoginBlockTime")[0]);
            if (WLC <= 0)
            {
                return;
            }
            if (WLBT > 0)
            {
                qrCheck = "SELECT *, CURRENT_TIMESTAMP as CT FROM logincount WHERE UserName = '" + Login1.UserName + "'";
                dsLastLogin = GetData(qrCheck, "WebCNS");
                if (dsLastLogin.Tables.Count > 0)
                {
                    if (dsLastLogin.Tables[0].Rows.Count > 0)
                    {
                        Count = Convert.ToInt32(dsLastLogin.Tables[0].Rows[0]["WCount"]);
                        PreviousTime = Convert.ToDateTime(dsLastLogin.Tables[0].Rows[0]["Laiks"]);
                        LastTime = Convert.ToDateTime(dsLastLogin.Tables[0].Rows[0]["CT"]);
                        if (PreviousTime.AddSeconds(WLBT) < LastTime)
                        {
                            Count = 1;
                            UpdateWrongLogin(Count);
                        }
                        else
                        {
                            Count += 1;
                            UpdateWrongLogin(Count);
                        }
                    }
                    else
                    {
                        Count = 1;
                        PreviousTime = DateTime.Now;
                        UpdateWrongLogin(Count);
                    }
                }

            }
            else
            {
                return;
            }

        }

        protected void UpdateWrongLogin(int NewCount)
        {
            string qrWhere = "";
            string qrUpdate = "SELECT UserName FROM logincount WHERE UserName = '" + Login1.UserName + "'";
            DataSet dsLastLogin = GetData(qrUpdate, "WebCNS");
            qrUpdate = "INSERT INTO ";
            if (dsLastLogin.Tables.Count > 0)
            {
                if (dsLastLogin.Tables[0].Rows.Count > 0)
                {
                    qrUpdate = "UPDATE ";
                    qrWhere = " WHERE UserName = '" + Login1.UserName + "'";
                }
            }
            qrUpdate = qrUpdate + "logincount SET UserName = '" + Login1.UserName + "', WCount = " + NewCount + ", Laiks = NULL " + qrWhere;
            GetData(qrUpdate, "WebCNS");
        }

        protected void DeleteWrongLogin()                           
        {
            string qrDel = "DELETE FROM logincount WHERE UserName = '" + Login1.UserName + "'";
            GetData(qrDel, "WebCNS");
        }

        private bool SiteSpecificAuthenticationMethod(string UserName, string Password)
        {
            // Insert code that implements a site-specific custom 
            // authentication method here.
            //
            // This example implementation always returns false.
            string QString = "SELECT * FROM users WHERE RecStatus=0 AND User='" + Login1.UserName + "' AND password=SHA('" + Login1.Password + "')";
            //dsLogin.Select(DataSourceSelectArguments.Empty);

            DataSet ds = GetData(QString, "WebCNS");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];

                    Session["UserName"] = row["User"];// ds.Tables[0].Columns["User"].ToString();
                    Session["UserEMail"] = row["Email"].ToString();
                    Session["IsLoggedIn"] = "1";
                    //Session["LongUserName"] = row["LongUsr"];
                    //ds = GetData("SELECT * FROM user_groups WHERE User='" + Session["UserName"] + "'", "mysqlConnectionString");
                    //if (ds.Tables[0].Rows.Count > 0)
                    //{
                    //    row = ds.Tables[0].Rows[0];
                        Session["UserGroups"] = row["Groups"];
                        string[] WhereGroups = Session["UserGroups"].ToString().Split(new char[] { ';' }, System.StringSplitOptions.RemoveEmptyEntries);
                        Session["WhereGroups"] = " OR AccessU LIKE '%;" + Session["UserName"] + ";%' OR AccessG LIKE '%;Authenticated users;%' OR AccessG LIKE '%;Everyone;%' ";
                        for (int i = 0; i <= WhereGroups.GetUpperBound(0); i++)
                        {
                            Session["WhereGroups"] = Session["WhereGroups"] + " OR AccessG LIKE '%;" + WhereGroups[i] + ";%'";
                        }
                        string TestAdmin = Session["UserGroups"].ToString();
                        if (TestAdmin.IndexOf(";Administrators;", StringComparison.CurrentCultureIgnoreCase) >= 0)
                        {
                            Session["IsAdmin"] = "1";
                        }
                        else
                        {
                            Session["IsAdmin"] = "0";
                        }
                    //}
                    //Session["LongUserName"] = row["LongUsr"]; //ds.Tables[0].Columns["LongUser"].ToString();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            bool Authenticated = false;
            Login1.FailureText = "Ielogošanās bloķēta!\n Sazinieties ar sistēmas administratoru.";
            if (!CheckWrongLogin())
            {
                e.Authenticated = Authenticated;
                return;
            }
            Login1.FailureText = "Ielogošanās neveiksmīga. Mēģiniet vēlreiz";
            if (Login1.UserName.Length > 20)
            {
                Login1.FailureText = "Lietotāja vārdam jābūt īsākam par 20 simboliem!";
                e.Authenticated = Authenticated;
                return;
            }
            if (Login1.Password.Length > 16)
            {
                Login1.FailureText = "Parolei jābūt īsākai par 16 simboliem!";
                e.Authenticated = Authenticated;
                return;
            }
            if (Login1.Password.Length < 4)
            {
                Login1.FailureText = "Parolei jābūt garākai par 3 simboliem!";
                e.Authenticated = Authenticated;
                return;
            }
            Authenticated = SiteSpecificAuthenticationMethod(Login1.UserName, Login1.Password);

            e.Authenticated = Authenticated;
            if (Authenticated == false)
            {
                AddWrongLogin();
            }
            else
            {
                UpdateWrongLogin(0);
            }
            //PreviousPage.Form.Controls[0] = "Logout";
            //Label LBTN = (Label) Page.PreviousPage.FindControl("lblLogin");
            //LBTN.Text = "Logout";
        }

        protected void cmdLogOut_Click(object sender, EventArgs e)
        {
            Session["UserName"] = null;//"guest"
            Session["IsAdmin"] = "0";
            Session["IsLoggedIn"] = null;
            Session["UserGroups"] = null;//";Guests;"
            Session["WhereGroups"] = null;// "AND (AccessU LIKE '%;guest;% OR AccessG LIKE '%;Guests;%')";
            Session["LongUserName"] = "";
            Session.Abandon();
            //Response.Redirect("~/Default.aspx");
        }



    }
}
